package com.boilermaker.lotterysystem.service.statusconvert.operator;

import com.boilermaker.lotterysystem.dao.dataobject.ActivityUserDO;
import com.boilermaker.lotterysystem.dao.mapper.ActivityUserMapper;
import com.boilermaker.lotterysystem.service.dto.ConvertStatusDTO;
import com.boilermaker.lotterysystem.service.enums.ActivityUserStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class UserStatusOperator extends AbstractStatusOperator {

    @Autowired
    private ActivityUserMapper activityUserMapper;

    @Override
    public Integer sequence() {
        return 1;
    }

    @Override
    public Boolean convertPolicy(ConvertStatusDTO dto) {

        Long activityId = dto.getActivityId();
        List<Long> userIds = dto.getUserIds();
        ActivityUserStatusEnum targetStatus = dto.getTargetUserStatus();

        if (activityId == null
                || CollectionUtils.isEmpty(userIds) || targetStatus == null) {
            return false;
        }

        List<ActivityUserDO> activityUserDOList =
                activityUserMapper.batchSelect(activityId, userIds);

        if (activityUserDOList == null) {
            return false;
        }

        // 若任一个人员的原状态与目标状态一致，则不能转换
        for (ActivityUserDO activityUserDO : activityUserDOList) {
            if (activityUserDO.getStatus().equalsIgnoreCase(targetStatus.name())) {
                return false;
            }
        }

        return true;
    }

    @Override
    public Boolean convert(ConvertStatusDTO dto) {

        Long activityId = dto.getActivityId();
        List<Long> userIds = dto.getUserIds();
        ActivityUserStatusEnum targetStatus = dto.getTargetUserStatus();

        try {
            activityUserMapper.batchUpdateStatus(activityId, userIds, targetStatus.name());
            return true;
        } catch (Exception e) {
            log.error("状态转换异常", e);
            return false;
        }
    }
}
